package com.sailors.common.task.provider.infra.remote;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.sailors.common.task.provider.faced.model.dto.execute.ExcelUploadDto;
import com.sailors.common.task.provider.faced.model.dto.execute.FileTaskCreateExecuteDto;
import com.sailors.common.task.provider.infra.design.common.util.ExcelUtil;
import com.sailors.common.task.provider.infra.system.config.cos.TencentCosProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.UUID;


/**
 * File upload remote service
 *
 * @description:
 * @author: cyj
 * @date 2023 -06-22 00:43:02
 */
@Slf4j
@Component
@RefreshScope
public class FileUploadRemoteService {
    @Resource
    private COSClient cosClient;
    @Resource
    private TencentCosProperties tencentCosProperties;

    /**
     * 获取Bucket
     * @param type type
     * @return Bucket
     */
    private TencentCosProperties.TencentCosBucket getBucket(String type) {
        Map<String, TencentCosProperties.TencentCosBucket> bucketMap = tencentCosProperties.getBucketMap();
        return bucketMap.getOrDefault(type, bucketMap.get(tencentCosProperties.getDefaultType()));
    }

    /**
     * 讲excelUploadDto转成excel并上传到cos
     * @param excelUploadDto
     * @return
     * @throws IOException
     */
    public String uploadExcel(ExcelUploadDto excelUploadDto) {

        if (null == excelUploadDto || CollectionUtil.isEmpty(excelUploadDto.getExcelHeads()) || CollectionUtil.isEmpty(excelUploadDto.getExcelRows())) {
            return null;
        }

        ByteArrayOutputStream outputStream = null;
        InputStream inputStream = null;
        try {

            outputStream = new ByteArrayOutputStream();
            // 讲数据转换成excel写入输出流
            ExcelUtil.write2OutputStream(outputStream, excelUploadDto);

            inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            TencentCosProperties.TencentCosBucket bucket = getBucket(null);
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(outputStream.size());


            String newFileName = UUID.randomUUID().toString();
            String dir = "files";
            String baseKey = dir + "/" + newFileName;
            String key = baseKey + "." + "xlsx";

            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket.getBucketName(), key, inputStream, metadata);
            PutObjectResult result = cosClient.putObject(putObjectRequest);
            if (log.isInfoEnabled()) {
                log.info("上传文件{}结果如下: {}", key, result);
            }
            return bucket.getUsePath() + key;
        } catch (Exception e) {
            log.info("upload excel failed, e: " + e.getMessage(), e);
            return null;
        } finally {
            IoUtil.close(outputStream);
            IoUtil.close(inputStream);
        }
    }
}
